package com.apache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 创建者 zhuhong  E-mail: zhuhong719@126.com
 * 创建时间：Jul 17, 2014 8:45:50 PM
 * 版本：
 * 类说明：
 * 修改者：
 * 修改时间：Jul 17, 2014 8:45:50 PM
 * 修改说明：
 */
public class Processor extends Thread{
	private InputStream in;
	private PrintStream out;
	private final static String WEB_ROOT="D:\\Tomcat6.0\\Tomcat6.0\\webapps\\";
	
	/**
	 * 初始化输入输出流
	 * @param socket
	 */
	public Processor(Socket socket){
		try {
			in=socket.getInputStream();
			out=new PrintStream(socket.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 逻辑线程
	 */
	public void run(){
		String fileName=parse(in);
		sendFile(fileName);
	}
	
	/**
	 * 解析http协议
	 * @param in
	 * @return
	 */
	public String parse(InputStream in){
		String fileName="";
		try {
			BufferedReader br=new BufferedReader(new InputStreamReader(in));
			String httpContent=br.readLine();
			String []content=httpContent.split(" ");
			fileName=content[1];
			System.out.println("method:"+content[0]+" request:"+fileName+" http-version:"+content[2]);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName.replace("/", "");
	}
	
	/**
	 * 返回错误码
	 * @param errorCode
	 * @param errorInfo
	 */
	public void sendErrorMessage(int errorCode,String errorInfo){
		try {
			out.println("HTTP/1.1 "+errorCode+" "+errorInfo);
			out.println("Content-Type:text/html");
			out.println();
			out.println("<html>");
			out.println("<title>Error Message");
			out.println("</title>");
			out.println("<body>");
			out.println("<h1>ErrorCode:"+errorCode+",Message:"+errorInfo+"</h1>");
			out.println("</body>");
			out.println("</html>");
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 返回请求文件
	 * @param fileName
	 */
	public void sendFile(String fileName){
		File file=new File(Processor.WEB_ROOT+fileName);
		if(!file.exists()){
			sendErrorMessage(404, "File Not Found!");
			return ;
		}
		try {
			InputStream in=new FileInputStream(file);
			byte content[]=new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.1 200 request");
			out.println("Content-Length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		}catch (FileNotFoundException e) {
			System.out.println("文件不存在:"+e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}
